package org.goldenport.g3.adapters

import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.goldenport.util.QSymbol
import org.goldenport.g3._
import org.goldenport.g3.messages._
import org.goldenport.g3.messages.event._
import org.goldenport.g3.events._
import org.goldenport.g3.events.event._

/**
 * @since   Mar. 31, 2011
 * @version Apr.  9, 2011
 * @author  ASAMI, Tomoharu
 */
class JaxRsAdapter(val driver: JaxRsDriver) extends G3Adapter {
  override def open_Adapter() {
    driver.open(context)
  }

  override def close_Adapter() {
    driver.close()
  }

  override protected def do_Action(content: AnyRef, parcel: G3Parcel, ctx: G3AgentContext): AnyRef = {
    content match {
      case cmd: G3Command => driver.execute(cmd, ctx)
    }
  }
}

object JaxRsAdapter {
  def create(bean: AnyRef): JaxRsAdapter = {
    new JaxRsAdapter(JaxRsDriver.create(bean))
  }

  def create(klass: Class[_]): JaxRsAdapter = {
    new JaxRsAdapter(JaxRsDriver.create(klass))
  }

  def create(className: String, ctx: G3Context): JaxRsAdapter = {
    new JaxRsAdapter(JaxRsDriver.create(className, ctx))
  }
}

class JaxRsDriver(val klass: Class[_]) extends G3Driver {
  protected def new_Agent(cmd: G3Command, ctx: G3AgentContext): JaxRsDriverAgent = {
    val wsapp = new javax.ws.rs.core.Application {
      override def getClasses(): java.util.Set[Class[_]] = {
        val res = new java.util.HashSet[Class[_]]()
        res.add(klass)
        println("JaxRsDriver.Application = " + res)
        res
      }
    }
    val container = new ServletContainer(wsapp)
    new JaxRsDriverAgent(cmd.uri, ctx, container)
  }
}

object JaxRsDriver {
  def create(bean: AnyRef): JaxRsDriver = {
    new JaxRsDriver(bean.getClass())
  }

  def create(klass: Class[_]): JaxRsDriver = {
    new JaxRsDriver(klass)
  }

  def create(className: String, ctx: G3Context): JaxRsDriver = {
    new JaxRsDriver(ctx.loadClass(className))
  }
}

class JaxRsDriverAgent(uri: String, context: G3AgentContext,
                       container: ServletContainer)
  extends ServletDriverAgent(uri, container, context) {
}
